<template>
  <div class="profile-password-form">
    <div class="form-header">
      <h3>修改密码</h3>
      <p>为了您的账户安全，请定期更换密码</p>
    </div>

    <el-form
      ref="formRef"
      :model="form"
      :rules="formRules"
      label-width="120px"
      size="large"
      @submit.prevent="handleSubmit"
    >
      <!-- 当前密码 -->
      <el-form-item label="当前密码" prop="currentPassword">
        <el-input
          v-model="form.currentPassword"
          type="password"
          placeholder="请输入当前密码"
          show-password
          clearable
        />
      </el-form-item>

      <!-- 新密码 -->
      <el-form-item label="新密码" prop="newPassword">
        <el-input
          v-model="form.newPassword"
          type="password"
          placeholder="请输入新密码（6-20个字符）"
          show-password
          clearable
          @input="onNewPasswordChange"
        />
        <div v-if="passwordStrengthTip" class="password-strength">
          {{ passwordStrengthTip }}
        </div>
      </el-form-item>

      <!-- 确认新密码 -->
      <el-form-item label="确认新密码" prop="confirmPassword">
        <el-input
          v-model="form.confirmPassword"
          type="password"
          placeholder="请再次输入新密码"
          show-password
          clearable
        />
      </el-form-item>

      <!-- 操作按钮 -->
      <el-form-item>
        <el-button
          type="primary"
          :loading="loading"
          class="submit-btn"
          @click="handleSubmit"
        >
          修改密码
        </el-button>
        <el-button @click="handleReset">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 安全提示 -->
    <div class="security-tips">
      <h4>密码安全建议：</h4>
      <ul>
        <li>密码长度至少6个字符，建议8个字符以上</li>
        <li>包含大小写字母、数字和特殊字符</li>
        <li>不要使用生日、姓名等容易猜测的信息</li>
        <li>定期更换密码，不要重复使用旧密码</li>
      </ul>
    </div>
  </div>
</template>

<script setup lang="ts">
import {
  ref,
  reactive,
  computed,
  type FormInstance,
  type FormRules
} from "vue";
import { ElMessage } from "element-plus";
import {
  changePasswordApi,
  validatePassword,
  formatErrorMessage,
  type ChangePasswordRequest
} from "@/api/user-profile-update";

interface Emits {
  (e: "success"): void;
}

const emit = defineEmits<Emits>();

// 表单引用
const formRef = ref<FormInstance>();

// 表单数据
const form = reactive<ChangePasswordRequest>({
  currentPassword: "",
  newPassword: "",
  confirmPassword: ""
});

// 加载状态
const loading = ref(false);

// 密码强度提示
const passwordStrengthTip = computed(() => {
  if (!form.newPassword) return "";

  const password = form.newPassword;
  const length = password.length;

  if (length < 6) {
    return "密码长度至少6个字符";
  }

  let strength = 0;
  if (/[a-z]/.test(password)) strength++;
  if (/[A-Z]/.test(password)) strength++;
  if (/[0-9]/.test(password)) strength++;
  if (/[^a-zA-Z0-9]/.test(password)) strength++;

  switch (strength) {
    case 1:
      return "密码强度：弱";
    case 2:
      return "密码强度：中等";
    case 3:
      return "密码强度：强";
    case 4:
      return "密码强度：很强";
    default:
      return "";
  }
});

// 表单验证规则
const formRules: FormRules = {
  currentPassword: [
    { required: true, message: "请输入当前密码", trigger: "blur" }
  ],
  newPassword: [
    { required: true, message: "请输入新密码", trigger: "blur" },
    {
      validator: (_rule, value, callback) => {
        if (!validatePassword(value)) {
          callback(new Error("新密码长度应为6-20个字符"));
        } else if (value === form.currentPassword) {
          callback(new Error("新密码不能与当前密码相同"));
        } else {
          callback();
        }
      },
      trigger: "blur"
    }
  ],
  confirmPassword: [
    { required: true, message: "请确认新密码", trigger: "blur" },
    {
      validator: (_rule, value, callback) => {
        if (value !== form.newPassword) {
          callback(new Error("两次输入的密码不一致"));
        } else {
          callback();
        }
      },
      trigger: "blur"
    }
  ]
};

// 新密码变化处理
const onNewPasswordChange = () => {
  // 触发确认密码验证
  if (form.confirmPassword) {
    formRef.value?.validateField("confirmPassword");
  }
};

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return;

  try {
    // 表单验证
    await formRef.value.validate();

    loading.value = true;

    // 调用API修改密码
    const response = await changePasswordApi(form);

    if (response.code === 200) {
      ElMessage.success("密码修改成功");
      emit("success");
      handleReset(); // 清空表单
    } else {
      ElMessage.error(response.message || "密码修改失败");
    }
  } catch (error) {
    console.error("修改密码失败:", error);
    ElMessage.error(formatErrorMessage(error));
  } finally {
    loading.value = false;
  }
};

// 重置表单
const handleReset = () => {
  form.currentPassword = "";
  form.newPassword = "";
  form.confirmPassword = "";

  // 清除验证状态
  formRef.value?.clearValidate();
};
</script>

<style scoped lang="scss">
// 响应式设计
@media (width <= 768px) {
  .profile-password-form {
    .el-form {
      :deep(.el-form-item__label) {
        width: 100px !important;
      }
    }
  }
}

.profile-password-form {
  max-width: 600px;

  .form-header {
    margin-bottom: 32px;

    h3 {
      margin: 0 0 8px;
      font-size: 20px;
      font-weight: 600;
      color: #1f2937;
    }

    p {
      margin: 0;
      color: #6b7280;
    }
  }

  .el-form {
    .el-form-item {
      margin-bottom: 24px;

      :deep(.el-form-item__label) {
        font-weight: 500;
        color: #374151;
      }

      :deep(.el-input__wrapper) {
        border-radius: 8px;
        transition: all 0.3s ease;

        &:hover {
          box-shadow: 0 0 0 1px #409eff;
        }

        &.is-focus {
          box-shadow: 0 0 0 2px rgb(64 158 255 / 20%);
        }
      }
    }

    .password-strength {
      margin-top: 8px;
      font-size: 12px;
      color: #6b7280;
    }

    .submit-btn {
      padding: 12px 32px;
      font-weight: 600;
      background: linear-gradient(135deg, #409eff 0%, #66b1ff 100%);
      border: none;
      transition: all 0.3s ease;

      &:hover {
        box-shadow: 0 8px 16px rgb(64 158 255 / 30%);
        transform: translateY(-2px);
      }

      &:active {
        transform: translateY(0);
      }

      &.is-loading {
        box-shadow: none;
        transform: none;
      }
    }
  }

  .security-tips {
    padding: 20px;
    margin-top: 32px;
    background: #f9fafb;
    border-left: 4px solid #409eff;
    border-radius: 8px;

    h4 {
      margin: 0 0 12px;
      font-size: 16px;
      font-weight: 600;
      color: #1f2937;
    }

    ul {
      padding-left: 20px;
      margin: 0;
      color: #6b7280;

      li {
        margin-bottom: 8px;
        line-height: 1.5;

        &:last-child {
          margin-bottom: 0;
        }
      }
    }
  }
}
</style>
